{% extends "base.html" %}

{% block title %}连接管理 - Alist-Sync{% endblock %}

{% block page_title %}连接管理{% endblock %}

{% block header_buttons %}
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addConnectionModal">
    <i class="bi bi-plus-lg"></i> 添加连接
</button>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card bg-dark-subtle">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover table-striped mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>名称</th>
                                <th>服务器地址</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="connections-table">
                            {% if connections %}
                                {% for conn in connections %}
                                <tr>
                                    <td>{{ conn.connection_id }}</td>
                                    <td>{{ conn.name }}</td>
                                    <td>{{ conn.server }}</td>
                                    <td>
                                        {% if conn.status == 'online' %}
                                        <span class="badge bg-success">在线</span>
                                        {% else %}
                                        <span class="badge bg-danger">离线</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ conn.created_at }}</td>
                                    <td>{{ conn.updated_at }}</td>
                                    <td>
                                        <div class="btn-group">
                                            <button class="btn btn-sm btn-primary edit-connection" data-conn-id="{{ conn.connection_id }}">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-info test-connection" data-conn-id="{{ conn.connection_id }}">
                                                <i class="bi bi-check2-circle"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger delete-connection" data-conn-id="{{ conn.connection_id }}">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            {% else %}
                                <tr>
                                    <td colspan="7" class="text-center">暂无连接</td>
                                </tr>
                            {% endif %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加连接模态框 -->
<div class="modal fade" id="addConnectionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark text-light">
            <div class="modal-header">
                <h5 class="modal-title">添加 Alist 连接</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="connectionForm">
                    <div class="mb-3">
                        <label for="connName" class="form-label">连接名称</label>
                        <input type="text" class="form-control bg-dark text-light" id="connName" required>
                    </div>
                    <div class="mb-3">
                        <label for="connServer" class="form-label">服务器地址</label>
                        <input type="url" class="form-control bg-dark text-light" id="connServer" placeholder="https://your-alist-server.com" required>
                    </div>
                    <div class="mb-3">
                        <label for="connUser" class="form-label">用户名</label>
                        <input type="text" class="form-control bg-dark text-light" id="connUser">
                    </div>
                    <div class="mb-3">
                        <label for="connPassword" class="form-label">密码</label>
                        <div class="input-group">
                            <input type="password" class="form-control bg-dark text-light" id="connPassword">
                            <button class="btn btn-outline-secondary bg-dark text-light password-toggle" type="button" data-target="connPassword">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="connToken" class="form-label">API 令牌</label>
                        <div class="input-group">
                            <input type="password" class="form-control bg-dark text-light" id="connToken" placeholder="可选，优先使用令牌认证">
                            <button class="btn btn-outline-secondary bg-dark text-light password-toggle" type="button" data-target="connToken">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="connProxy" class="form-label">代理设置 (可选)</label>
                        <input type="text" class="form-control bg-dark text-light" id="connProxy" placeholder="http://proxy:port">
                    </div>
                    <div class="mb-3">
                        <label for="connMaxRetry" class="form-label">最大重试次数</label>
                        <input type="number" class="form-control bg-dark text-light" id="connMaxRetry" value="3" min="0" max="10">
                    </div>
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="connInsecure">
                        <label class="form-check-label" for="connInsecure">允许不安全的 HTTPS 连接 (自签名证书)</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info" id="testConnectionBtn">测试连接</button>
                <button type="button" class="btn btn-primary" id="saveConnectionBtn">保存连接</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑连接模态框 -->
<div class="modal fade" id="editConnectionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark text-light">
            <div class="modal-header">
                <h5 class="modal-title">编辑 Alist 连接</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editConnectionForm">
                    <input type="hidden" id="editConnId">
                    <div class="mb-3">
                        <label for="editConnName" class="form-label">连接名称</label>
                        <input type="text" class="form-control bg-dark text-light" id="editConnName" required>
                    </div>
                    <div class="mb-3">
                        <label for="editConnServer" class="form-label">服务器地址</label>
                        <input type="url" class="form-control bg-dark text-light" id="editConnServer" placeholder="https://your-alist-server.com" required>
                    </div>
                    <div class="mb-3">
                        <label for="editConnUser" class="form-label">用户名</label>
                        <input type="text" class="form-control bg-dark text-light" id="editConnUser">
                    </div>
                    <div class="mb-3">
                        <label for="editConnPassword" class="form-label">密码</label>
                        <div class="input-group">
                            <input type="password" class="form-control bg-dark text-light" id="editConnPassword">
                            <button class="btn btn-outline-secondary bg-dark text-light password-toggle" type="button" data-target="editConnPassword">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editConnToken" class="form-label">API 令牌</label>
                        <div class="input-group">
                            <input type="password" class="form-control bg-dark text-light" id="editConnToken" placeholder="可选，优先使用令牌认证">
                            <button class="btn btn-outline-secondary bg-dark text-light password-toggle" type="button" data-target="editConnToken">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editConnProxy" class="form-label">代理设置 (可选)</label>
                        <input type="text" class="form-control bg-dark text-light" id="editConnProxy" placeholder="http://proxy:port">
                    </div>
                    <div class="mb-3">
                        <label for="editConnMaxRetry" class="form-label">最大重试次数</label>
                        <input type="number" class="form-control bg-dark text-light" id="editConnMaxRetry" value="3" min="0" max="10">
                    </div>
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="editConnInsecure">
                        <label class="form-check-label" for="editConnInsecure">允许不安全的 HTTPS 连接 (自签名证书)</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info" id="editTestConnectionBtn">测试连接</button>
                <button type="button" class="btn btn-primary" id="updateConnectionBtn">更新连接</button>
            </div>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content bg-dark text-light">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除此连接吗？该操作不可恢复，且可能影响依赖此连接的同步任务。</p>
                <input type="hidden" id="deleteConnId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 添加连接事件
        document.getElementById('saveConnectionBtn').addEventListener('click', function() {
            // 验证必填字段
            const connName = document.getElementById('connName');
            const connServer = document.getElementById('connServer');
            
            if (!connName.value.trim()) {
                showMessage('warning', '请输入连接名称');
                connName.focus();
                return;
            }
            
            if (!connServer.value.trim()) {
                showMessage('warning', '请输入服务器地址');
                connServer.focus();
                return;
            }
            
            // 禁用按钮，显示加载状态
            this.disabled = true;
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
            
            // 获取连接状态 - 使用测试结果的状态
            const connectionForm = document.getElementById('connectionForm');
            let connectionStatus = connectionForm.dataset.connectionStatus || 'offline';
            
            // 准备表单数据
            const connection = {
                name: connName.value,
                server: connServer.value,
                username: document.getElementById('connUser').value,
                password: document.getElementById('connPassword').value,
                token: document.getElementById('connToken').value,
                proxy: document.getElementById('connProxy').value,
                max_retry: document.getElementById('connMaxRetry').value,
                insecure: document.getElementById('connInsecure').checked,
                status: connectionStatus
            };
            
            // 发送保存请求
            fetch('/api/connections', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(connection)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                showMessage('success', '连接已添加');
                hideAddModal();
                
                // 重新加载列表
                setTimeout(() => {
                    location.reload();
                }, 1000);
            })
            .catch(error => {
                console.error('保存连接失败:', error);
                showMessage('danger', '保存连接失败: ' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = '保存连接';
            });
        });
        
        // 测试连接按钮 - 适用于新建模式
        document.getElementById('testConnectionBtn').addEventListener('click', function() {
            const server = document.getElementById('connServer').value;
            if (!server) {
                showMessage('warning', '请输入服务器地址');
                return;
            }
            
            // 禁用按钮，显示加载状态
            this.disabled = true;
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 测试中...';
            
            // 准备测试数据
            const testData = {
                server: server,
                username: document.getElementById('connUser').value,
                password: document.getElementById('connPassword').value,
                token: document.getElementById('connToken').value,
                insecure: document.getElementById('connInsecure').checked
            };
            
            // 发送测试请求
            fetch('/api/test-connection', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(testData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                // 保存连接状态到表单中，以便后续保存时使用
                const connectionForm = document.getElementById('connectionForm');
                connectionForm.dataset.connectionStatus = data.data.connection_status;
                
                if (data.status === 'success') {
                    // 如果获取到了新令牌，更新令牌输入框
                    if (data.data && data.data.token) {
                        document.getElementById('connToken').value = data.data.token;
                    }
                    
                    showMessage('success', '连接测试成功');
                } else {
                    showMessage('danger', data.message || '连接测试失败');
                }
            })
            .catch(error => {
                console.error('测试连接失败:', error);
                showMessage('danger', '测试连接失败: ' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = originalHTML;
            });
        });
        
        // 编辑连接按钮
        document.querySelectorAll('.edit-connection').forEach(button => {
            button.addEventListener('click', function() {
                const connId = this.getAttribute('data-conn-id');
                
                // 禁用按钮，显示加载状态
                this.disabled = true;
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                
                // 通过API获取连接信息
                fetch(`/api/connections/${connId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取连接信息失败');
                    }
                    return response.json();
                })
                .then(conn => {
                    document.getElementById('editConnId').value = conn.connection_id;
                    document.getElementById('editConnName').value = conn.name;
                    document.getElementById('editConnServer').value = conn.server;
                    document.getElementById('editConnUser').value = conn.username;
                    
                    // 设置密码值
                    if(conn.password) {
                        document.getElementById('editConnPassword').value = conn.password;
                    }
                    
                    document.getElementById('editConnToken').value = conn.token || '';
                    document.getElementById('editConnProxy').value = conn.proxy || '';
                    document.getElementById('editConnMaxRetry').value = conn.max_retry || 3;
                    document.getElementById('editConnInsecure').checked = conn.insecure === true;
                    
                    // 保存连接状态到表单数据中
                    const connectionForm = document.getElementById('editConnectionForm');
                    connectionForm.dataset.connectionStatus = conn.status || 'offline';
                    
                    // 显示模态框
                    new bootstrap.Modal(document.getElementById('editConnectionModal')).show();
                })
                .catch(error => {
                    console.error('获取连接信息失败:', error);
                    alert('获取连接信息失败: ' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    this.disabled = false;
                    this.innerHTML = originalHTML;
                });
            });
        });
        
        // 更新连接按钮
        document.getElementById('updateConnectionBtn').addEventListener('click', function() {
            // 获取表单数据
            const connId = document.getElementById('editConnId').value;
            
            // 显示加载状态
            this.disabled = true;
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 更新中...';
            
            // 获取连接状态
            const connectionForm = document.getElementById('editConnectionForm');
            const connectionStatus = connectionForm.dataset.connectionStatus || 'offline';
            
            // 调试日志
            console.log("更新连接前的状态:", connectionStatus, "表单数据:", connectionForm.dataset);
            
            // 构建连接数据
            const connection = {
                connection_id: parseInt(connId),
                name: document.getElementById('editConnName').value,
                server: document.getElementById('editConnServer').value,
                username: document.getElementById('editConnUser').value,
                password: document.getElementById('editConnPassword').value,
                token: document.getElementById('editConnToken').value,
                proxy: document.getElementById('editConnProxy').value,
                max_retry: document.getElementById('editConnMaxRetry').value,
                insecure: document.getElementById('editConnInsecure').checked,
                status: connectionStatus
            };
            
            // 发送更新请求
            fetch(`/api/connections/${connId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(connection)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                showMessage('success', data.message);
                hideEditModal();
                
                // 重新加载列表
                setTimeout(() => {
                    location.reload();
                }, 1000);
            })
            .catch(error => {
                console.error('更新连接失败:', error);
                showMessage('danger', '更新连接失败: ' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = '更新连接';
            });
        });
        
        // 测试连接按钮 - 适用于编辑模式
        document.getElementById('editTestConnectionBtn').addEventListener('click', function() {
            // 禁用按钮，显示加载状态
            this.disabled = true;
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 测试中...';
            
            // 获取连接ID
            const connId = document.getElementById('editConnId').value;
            
            // 准备测试数据
            const testData = {
                connection_id: parseInt(connId),
                server: document.getElementById('editConnServer').value,
                username: document.getElementById('editConnUser').value,
                token: document.getElementById('editConnToken').value,
                insecure: document.getElementById('editConnInsecure').checked
            };
            
            // 只有当密码字段有值时才包含在请求中
            const password = document.getElementById('editConnPassword').value;
            if (password) {
                testData.password = password;
            }
            
            // 发送测试请求
            fetch('/api/test-connection', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(testData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                // 保存连接状态到表单中，以便后续保存时使用
                const connectionForm = document.getElementById('editConnectionForm');
                connectionForm.dataset.connectionStatus = data.data.connection_status;
                
                // 调试日志
                console.log("测试连接后设置状态:", data.data.connection_status);
                
                if (data.status === 'success') {
                    // 如果获取到了新令牌，更新令牌输入框
                    if (data.data && data.data.token) {
                        document.getElementById('editConnToken').value = data.data.token;
                    }
                    
                    // 立即更新UI显示连接状态
                    const statusBadgeHtml = `<span class="badge bg-success">在线</span>`;
                    document.querySelector(`.test-connection[data-conn-id="${connId}"]`)
                        .closest('tr')
                        .querySelector('td:nth-child(4)')
                        .innerHTML = statusBadgeHtml;
                    
                    showMessage('success', '连接测试成功，状态已更新为"在线"');
                } else {
                    // 立即更新UI显示连接状态
                    const statusBadgeHtml = `<span class="badge bg-danger">离线</span>`;
                    document.querySelector(`.test-connection[data-conn-id="${connId}"]`)
                        .closest('tr')
                        .querySelector('td:nth-child(4)')
                        .innerHTML = statusBadgeHtml;
                    
                    showMessage('danger', data.message || '连接测试失败');
                }
            })
            .catch(error => {
                console.error('测试连接失败:', error);
                showMessage('danger', '测试连接失败: ' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = originalHTML;
            });
        });
        
        // 删除连接按钮事件
        document.querySelectorAll('.delete-connection').forEach(button => {
            button.addEventListener('click', function() {
                const connId = this.getAttribute('data-conn-id');
                const connName = this.closest('tr').querySelector('td:nth-child(2)').textContent;
                
                if (!confirm(`确定要删除连接 "${connName}" 吗？此操作不可恢复。`)) {
                    return;
                }
                
                // 禁用按钮，显示加载状态
                this.disabled = true;
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                
                fetch(`/api/connections/${connId}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    showMessage('success', `连接 "${connName}" 已删除`);
                    
                    // 从表格中移除该行
                    this.closest('tr').remove();
                    
                    // 如果表格为空，显示"暂无连接"消息
                    const table = document.getElementById('connections-table');
                    if (table.children.length === 0) {
                        table.innerHTML = '<tr><td colspan="7" class="text-center">暂无连接</td></tr>';
                    }
                })
                .catch(error => {
                    console.error('删除连接失败:', error);
                    showMessage('danger', '删除连接失败: ' + error.message);
                    
                    // 恢复按钮状态
                    this.disabled = false;
                    this.innerHTML = originalHTML;
                });
            });
        });
        
        // 测试连接按钮（列表中的）
        document.querySelectorAll('.test-connection').forEach(button => {
            button.addEventListener('click', function() {
                const connId = this.getAttribute('data-conn-id');
                
                // 显示测试中状态
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                this.disabled = true;
                
                // 获取该连接的状态标签
                const statusBadge = this.closest('tr').querySelector('td:nth-child(4) .badge');
                
                // 获取该连接的信息
                fetch(`/api/connections/${connId}`)
                .then(response => response.json())
                .then(connection => {
                    // 如果获取连接信息成功，进行连接测试
                    if (connection) {
                        const connectionData = {
                            connection_id: parseInt(connId), // 使用connection_id
                            server: connection.server,
                            username: connection.username,
                            password: connection.password,
                            token: connection.token
                        };
                        
                        return fetch('/api/test-connection', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(connectionData),
                        });
                    } else {
                        throw new Error('无法获取连接信息');
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 立即更新UI显示
                        if (statusBadge) {
                            statusBadge.className = 'badge bg-success';
                            statusBadge.textContent = '在线';
                        }
                        
                        showMessage('success', '连接测试成功');
                    } else {
                        // 立即更新UI显示
                        if (statusBadge) {
                            statusBadge.className = 'badge bg-danger';
                            statusBadge.textContent = '离线';
                        }
                        
                        showMessage('danger', `连接测试失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('测试连接失败:', error);
                    
                    // 出错时更新为离线状态
                    if (statusBadge) {
                        statusBadge.className = 'badge bg-danger';
                        statusBadge.textContent = '离线';
                    }
                    
                    showMessage('danger', `测试连接失败: ${error.message}`);
                })
                .finally(() => {
                    // 恢复按钮状态
                    this.innerHTML = originalHTML;
                    this.disabled = false;
                });
            });
        });

        // 密码显示/隐藏切换功能
        document.querySelectorAll('.password-toggle').forEach(button => {
            button.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const inputField = document.getElementById(targetId);
                const icon = this.querySelector('i');
                
                if (inputField.type === 'password') {
                    inputField.type = 'text';
                    icon.classList.remove('bi-eye');
                    icon.classList.add('bi-eye-slash');
                } else {
                    inputField.type = 'password';
                    icon.classList.remove('bi-eye-slash');
                    icon.classList.add('bi-eye');
                }
            });
        });

        // 辅助函数：显示消息提示
        function showMessage(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show fixed-top w-50 mx-auto mt-3`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            document.body.appendChild(alertDiv);
            
            // 3秒后自动关闭
            setTimeout(() => {
                alertDiv.classList.remove('show');
                setTimeout(() => {
                    document.body.removeChild(alertDiv);
                }, 150);
            }, 3000);
        }
        
        // 辅助函数：隐藏添加模态框
        function hideAddModal() {
            const modal = bootstrap.Modal.getInstance(document.getElementById('addConnectionModal'));
            if (modal) {
                modal.hide();
            }
        }
        
        // 辅助函数：隐藏编辑模态框
        function hideEditModal() {
            const modal = bootstrap.Modal.getInstance(document.getElementById('editConnectionModal'));
            if (modal) {
                modal.hide();
            }
        }
    });
</script>
{% endblock %} 